package cn.gx.kevin.config;

import cn.gx.kevin.common.utils.IRequestInterceptor;
import cn.gx.kevin.common.utils.RequestInterceptor;
import cn.gx.kevin.common.utils.SysConfigParams;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsProcessor;
import org.springframework.web.cors.DefaultCorsProcessor;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.*;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

    @Autowired
    private Environment environment;

    private static final Logger logger = LoggerFactory.getLogger(WebConfig.class);

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.WriteNullListAsEmpty, // List类型字段为null时输出[]而非null
                SerializerFeature.WriteMapNullValue, // 显示空字段
                SerializerFeature.WriteNullStringAsEmpty, // 字符串类型字段为null时间输出""而非null
                SerializerFeature.PrettyFormat, // 美化json输出，否则会作为整行输出
                SerializerFeature.WriteDateUseDateFormat, // 时间格式yyyy-MM-dd HH: mm: ss
                SerializerFeature.DisableCircularReferenceDetect);  // 禁用循环引用检测

        // 3.在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        // 处理中文乱码问题
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XML);
        supportedMediaTypes.add(MediaType.TEXT_HTML);
        supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
        supportedMediaTypes.add(MediaType.TEXT_PLAIN);
        supportedMediaTypes.add(MediaType.TEXT_XML);
        fastConverter.setSupportedMediaTypes(supportedMediaTypes);
        converters.add(fastConverter);
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        //创建权限拦截器
        IRequestInterceptor authInterceptor = new  AuthInterceptor();
        RequestInterceptor handlerInterceptor = new RequestInterceptor(authInterceptor);
        //日志拦截器
        IRequestInterceptor logInterceptor = new LogInterceptor() ;
        handlerInterceptor.setRequestInterceptor(logInterceptor);

        //添加配置的拦截器
        InterceptorRegistration addInterceptor = registry.addInterceptor(handlerInterceptor);

        // 排除配置
        addInterceptor.excludePathPatterns("/favicon.ico");
        addInterceptor.excludePathPatterns("/error");
        addInterceptor.excludePathPatterns("/static/**");//排除静态资源
        addInterceptor.excludePathPatterns("/upolad/**");//排除上传目录
        // 拦截配置
        addInterceptor.addPathPatterns("/**");
    }
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 允许任何域名使用
        corsConfiguration.addAllowedHeader("*"); // 允许任何头
        corsConfiguration.addAllowedMethod("*"); // 允许任何方法（post、get等）
        return corsConfiguration;
    }
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置
        CorsFilter filter = new GlobalCorsFilter(source);
        CorsProcessor processor = new DefaultCorsProcessor();
        filter.setCorsProcessor(processor);
        return filter;
    }

    //处理静态资源访问
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        String uploadDir = SysConfigParams.getUploadRootDir(environment);
        logger.info("UploadRootDir ="+uploadDir);
        registry.addResourceHandler("/upload/files/**").addResourceLocations("file:" + uploadDir  +"files" + File.separator );
        registry.addResourceHandler("/upload/images/**").addResourceLocations("file:" + uploadDir  +"images"+ File.separator );
        registry.addResourceHandler("/upload/xls/**").addResourceLocations("file:" + uploadDir +"xls"+ File.separator );
        registry.addResourceHandler("/upload/tmpls/**").addResourceLocations("file:" + uploadDir +"tmpls"+ File.separator );
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");   //根目录下的任何静态资源被请求时，都到/static/目录下去找静态资源
        registry.addResourceHandler("/*.ico").addResourceLocations("classpath:/static/");
        super.addResourceHandlers(registry);
    }
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("login");
    }
}
